﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;
using System.Data.OleDb;
using System.Configuration;
using System.Net.NetworkInformation;
using System.Net;
using System.Web;
using ZG_member;
using ZG_member.Model;
using ZG_member.BLL;
using System.Data.SqlClient;


namespace ZG_member
{
    public partial class SendMsgsForm : Form
    {
       



        public SendMsgsForm()
        {
            InitializeComponent();
            skinEngine1.SkinFile = Application.StartupPath + ConfigurationManager.AppSettings["Skin"];
        }
        List<string> phone = new List<string>();
        //SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["fuwuqi"]);
        //SqlCommand cmd;
        //SqlDataReader dr;
        public SendMsgsForm(List<string> phe)
        {
            InitializeComponent();
            skinEngine1.SkinFile = Application.StartupPath + ConfigurationManager.AppSettings["Skin"];
            phone = phe;
        }
        /// <summary>
        /// 获取md5码
        /// </summary>
        /// <param name="source">待转换字符串</param>
        /// <returns>md5加密后的字符串</returns>
        public string getMD5(string source)
        {
            string result = "";
            try
            {
                MD5 getmd5 = new MD5CryptoServiceProvider();
                byte[] targetStr = getmd5.ComputeHash(UnicodeEncoding.UTF8.GetBytes(source));
                result = BitConverter.ToString(targetStr).Replace("-", "");
                return result;
            }
            catch (Exception)
            {
                return "0";
            }

        }


        ZG_member.sms.WebService sms = new ZG_member.sms.WebService();

        //国金的账户密码
        //string sn = "DXX-VVV-010-03507";
        //string password = "642073";
        //string mobile = "";
        //string cont = "";
        //string subcode = "";
        //string stime = "";

        //短信账户密码
        string sn = "";
        string password = "";
        string mobile = "";
        string cont = "";
        string subcode = "";
        string stime = "";



        public void sendMsg(string content,string txtcontacts)
        {
            cbxSendT.Enabled = false;
            //MD5加密密码
            string pwd = getMD5(sn + password);

            string[] contacts = txtcontacts.Split(',');
            cont = content;

            long startTime, endTime;
            startTime = DateTime.Now.Ticks;//记录当前时刻

            for (int i = 0; i < contacts.Length; i++)
            {

                mobile = contacts[i];
                if (mobile == "") 
                {
                    continue;
                }
                if (cbxSendT.Checked)
                {
                    stime = dtpSendMsgTime.Value.ToString("");
                }
                else
                {
                    stime = "";
                }

                //发送短信
                //定时时间，扩展码和rrid可以为空，当rrid(唯一标识串)为空时，返回系统指定rrid
                //string result = "";
                string result = sms.mt(sn, pwd, mobile, cont, subcode, stime, "");


                endTime = DateTime.Now.Ticks;
                TimeSpan sendSpan = new TimeSpan(endTime - startTime);
                if (result.StartsWith("-"))
                {
                    rtbxSendStatus.AppendText("[" + DateTime.Now + "]" + mobile + ":" + result);

                }
                else
                {
                    rtbxSendStatus.AppendText("[" + DateTime.Now + "]" + mobile + ":发送成功,发送用时" + sendSpan.ToString());

                }
                rtbxSendStatus.AppendText("\n");
            }
            cbxSendT.Enabled = true;
        }
        
        
        public void shouxin() {
            //获取各个参数
            //getValues();
            //MD5加密密码
            string pwd = getMD5(sn + password);
            //接收信息
            string result = sms.mo(sn, pwd);
            string[] temp = result.Split('\n');

            string rich_output = "";

            ZG_member.BLL.collection cbll = new ZG_member.BLL.collection();
            ZG_member.BLL.memberInfo mbll = new ZG_member.BLL.memberInfo();
            ZG_member.BLL.SMS sbll = new ZG_member.BLL.SMS();
            //ZG_member.BLL.memberInfo membll = new ZG_member.BLL.memberInfo();
            if (temp.Length > 0)
            {
                //rich_output.Refresh();
                for (int i = 0; i < temp.Length; i++)
                {
                    //或者为对数据库操作
                    //string[] temp_detail = temp[i].Split(',');
                    //for (int j = 0; j < temp_detail.Length; j++)
                    //{                        
                    //}
                    //对接受信息进行url解码

                    string resultStr = HttpUtility.UrlDecode(temp[i], Encoding.GetEncoding("gb2312"));
                    //rich_output += resultStr;
                    rich_output = "128142073,180032,13910587948,a,2013-05-17 09:45:25";
                    //127895018,180032,15010633086,a,2013-05-16 11:10:37
                    //MessageBox.Show(" " + rich_output);
                    ZG_member.BLL.Duanxingneirong blldx = new ZG_member.BLL.Duanxingneirong();
                    if (rich_output != "1")
                    {
                        string[] rich = rich_output.Split(',');

                        if (rich[3].ToUpper() == "A" || rich[3].ToUpper() == "B" || rich[3].ToUpper() == "C" || rich[3].ToUpper() == "D")
                            {
                                ZG_member.Model.collection coll = new ZG_member.Model.collection();

                                //StringBuilder strSql = new StringBuilder();
                                //strSql.Append("select id,memberId,memberCardId,memberName,sex,mobile,Tel,Email,IDNumber,birthDay,cardType,Balance,point,status,createDate,expiresDate,consume,memo,pwd,Marriage,Zip,Address,AreasID,MemberType,shifouhuixing,tuiguangren ");
                                //strSql.Append(" FROM memberInfo ");
                                //if (rich[2].Trim() != "")
                                //{
                                //    strSql.Append(" where  Tel = " + rich[2]);
                                //}
                                
                                //cmd = new SqlCommand(strSql.ToString(), conn);
                                //conn.Open();
                                //dr =  cmd.ExecuteReader();
                                //ZG_member.Model.memberInfo memb = new Model.memberInfo();
                                //while (dr.Read())
                                //{
                                //    memb.id = int.Parse(dr["id"].ToString());
                                //    memb.memberId = dr["memberId"].ToString();
                                //    memb.memberCardId = dr["memberCardId"].ToString();
                                //    memb.memberName = dr["memberName"].ToString();
                                //    memb.sex = bool.Parse(dr["sex"].ToString());
                                //    memb.mobile = dr["mobile"].ToString();
                                //    memb.Tel = dr["Tel"].ToString();
                                //    memb.Email = dr["Email"].ToString();
                                //    memb.IDNumber = dr["IDNumber"].ToString();
                                //    memb.birthDay = DateTime.Parse(dr["birthDay"].ToString());
                                //    memb.cardType = int.Parse(dr["cardType"].ToString());
                                //    memb.Balance = decimal.Parse(dr["Balance"].ToString());
                                //    memb.point = int.Parse(dr["point"].ToString());
                                //    memb.status = int.Parse(dr["status"].ToString());
                                //    memb.createDate = DateTime.Parse(dr["createDate"].ToString());
                                //    memb.expiresDate = DateTime.Parse(dr["expiresDate"].ToString());
                                //    memb.consume = decimal.Parse(dr["consume"].ToString());
                                //    memb.memo = dr["memo"].ToString();
                                //    memb.pwd = dr["pwd"].ToString();
                                //    memb.Marriage = dr["Marriage"].ToString();
                                //    memb.Zip = dr["Zip"].ToString();
                                //    memb.Address = dr["Address"].ToString();
                                //    memb.AreasID = int.Parse(dr["AreasID"].ToString());
                                //    memb.MemberType = dr["MemberType"].ToString();
                                //    memb.Shifoushouxin = dr["shifouhuixing"].ToString();
                                //    memb.Tuiguangren = dr["tuiguangren"].ToString();
                                //}
                                if (rich[2] == null)
                                {
                                    continue;
                                }
                                ZG_member.Model.memberInfo memb = mbll.GetModelList(" Tel = '" + rich[2]+"'")[0];
                                if (memb == null)
                                {
                                    continue;
                                }
                                coll.Phone = rich[2];
                                coll.Collectionsresult = rich[3];
                                coll.Time = DateTime.Parse(rich[4]);
                                coll.Memberid = memb.memberId;
                                //if (memb.Shifoushouxin == "1")
                                //{
                                //    continue;
                                //}
                                if (cbll.add(coll))
                                {
                                    mbll.shifoushouxinUpdate("1", memb.memberId);
                                    ZG_member.Model.SMS smodle = sbll.GetListmodel();
                                    memb.point = memb.point + int.Parse(smodle.SMSjifen1);
                                    if (mbll.Updatepoint(memb))
                                    {
                                        ZG_member.Model.Duanxingneirong dxmodle = blldx.getmodel(2);
                                        string huixingneirong = string.Format(dxmodle.Fasongneirong, smodle.SMSjifen1, memb.point + int.Parse(smodle.SMSjifen1));
                                        try
                                        {
                                            if (faxing == "1")
                                            {
                                                sendMsg(huixingneirong, rich[2]);
                                            }

                                        }
                                        catch (Exception)
                                        {
                                            MessageBox.Show("由于计算机未连网，不能发信息！");

                                        }
                                       
                                    } 
                                } 
                            }
                        
                    }
                    //rich_output.Refresh();
                }
            }
            else
            {
               // rich_output.AppendText("无可接收信息" + "\r");
            }
            

        }

        string faxing = ConfigurationManager.AppSettings["faxin"];
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            dtpSendMsgTime.Enabled = cbxSendT.Checked;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {



            sendMsg(this.txtContent.Text,this.txtContacts.Text);
        }

        private void btnLeadingIn_Click(object sender, EventArgs e)
        {
            try
            {

                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "Excel文件|*.xls|Excel文件|*.xlsx";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {

                    FileInfo fileInfo = new FileInfo(openFileDialog.FileName);
                    string filePath = fileInfo.FullName;
                    try
                    {
                        // string connExcel = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0";
                        string connExcel = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended properties=\"Excel 12.0;Imex=1;HDR=Yes;\"";
                        OleDbConnection oleDbConnection = new OleDbConnection(connExcel);
                        oleDbConnection.Open();
                        DataTable dataTable = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                        string tableName = dataTable.Rows[0][2].ToString().Trim();
                        tableName = "[" + tableName.Replace("'", "") + "]";
                        string query = "SELECT * FROM " + tableName;
                        DataSet dataSet = new DataSet();
                        OleDbDataAdapter oleAdapter = new OleDbDataAdapter(query, connExcel);
                        oleAdapter.Fill(dataSet, tableName);
                        oleDbConnection.Close();
                        DataTable dt = dataSet.Tables[0];  //将数据和dataGridView绑   
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            txtContacts.Text += dt.Rows[i][0] + ",";
                        }
                    }
                    catch
                    {
                        string connExcel = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0";
                        // string connExcel = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended properties=\"Excel 12.0;Imex=1;HDR=Yes;\"";
                        OleDbConnection oleDbConnection = new OleDbConnection(connExcel);
                        oleDbConnection.Open();
                        DataTable dataTable = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                        string tableName = dataTable.Rows[0][2].ToString().Trim();
                        tableName = "[" + tableName.Replace("'", "") + "]";
                        string query = "SELECT * FROM " + tableName;
                        DataSet dataSet = new DataSet();
                        OleDbDataAdapter oleAdapter = new OleDbDataAdapter(query, connExcel);
                        oleAdapter.Fill(dataSet, tableName);
                        oleDbConnection.Close();
                        DataTable dt = dataSet.Tables[0];  //将数据和dataGridView绑   
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            txtContacts.Text += dt.Rows[i][0] + ",";
                        }
                    }
                }
            }
            catch
            {
                MessageBox.Show("表格正处于打开状态或外部表不是所规定的表格类型");
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtContacts.Text = "";
            txtContent.Text = "【国金黄金】";
            rtbxSendStatus.Text = "";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            txtContacts.Text = "";
        }

        private void SendMsgsForm_Load(object sender, EventArgs e)
        {
            MessageBox.Show("对不起，您未开通此功能");
            this.Close();

            this.Opacity = 0;
            this.timer1.Start();

            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://sdk2.entinfo.cn:8060/webservice.asmx");
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    resp.Close();
                }
                else
                {
                    this.btnSend.Enabled = false;
                    this.button2.Enabled = false;
                    System.Windows.Forms.MessageBox.Show("由于您的电脑未联网！短信功能无法使用！");
                }
            }
            catch (WebException webex)
            {

                this.btnSend.Enabled = false;
                this.button2.Enabled = false;
                System.Windows.Forms.MessageBox.Show("由于您的电脑未联网！短信功能无法使用！");

            }
            
            txtTextChanged();
            if (phone.Count != 0)
            {
                for (int i = 0; i < phone.Count; i++)
                {
                    this.txtContacts.Text += phone[i]+",";
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //timer开启
            this.Left += 2;
            this.Opacity += 0.1;
            if (Opacity == 1)
            {
                this.timer1.Stop();

            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            //timer关闭
            this.Top = this.Top + 10;
            this.Opacity = this.Opacity - 0.06;
            if (Opacity <= 0)
            {
                this.timer2.Stop();
                this.Close();
            }
        }
        int flag = 0;
        private void SendMsgsForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (flag == 0)
            {
                e.Cancel = true;
                flag = 1;
                this.timer2.Start();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string pwd = getMD5(sn + password);

            string balance = sms.balance(sn, pwd);

            rtbxSendStatus.AppendText("剩余：" + balance + "\n");
        }

        private void txtTextChanged()
        {

            int count = txtContent.TextLength / 65;
            int leftLength = 65 - (txtContent.TextLength - count * 65);
            lblMsgAlert.Text = leftLength.ToString() + "/" + (count + 1);
        }

        private void txtContent_TextChanged(object sender, EventArgs e)
        {
            txtTextChanged();
        }
        
    }
}
